import { http } from '../utils/http'
import AsyncStorage from "@react-native-async-storage/async-storage";

// 文件预签名地址 Response VO
export interface FilePresignedUrlRespVO {
  // 文件配置编号
  configId: number
  // 文件上传 URL
  uploadUrl: string
  // 文件 URL
  url: string
  // 文件路径
  path: string
}

// 获取文件预签名地址
export const getFilePresignedUrl = (name: string, directory?: string) => {
  // 构建文件路径，如果有目录则加上目录前缀
  const path = directory ? `${directory}/${name}` : name
  console.log(name)
  return http.get<FilePresignedUrlRespVO>('/infra/file/presigned-url', {
    name, path, directory
  })
}

// 创建文件记录
export const createFile = (data: {
  configId: number
  url: string
  path: string
  name: string
  type: string
  size: number
}) => {
  return http.post('/infra/file/create', data)
}

// 直接上传文件到后端（备用方案）
export const uploadFileDirectly = async (
  file: {
    uri: string
    type: string
    name: string
    size: number
  }
) => {
  const formData = new FormData()
  formData.append('file', {
    uri: file.uri,
    type: file.type,
    name: file.name,
    size: file.size,
  } as any)

  // 获取 token
  const token = await AsyncStorage.getItem("accessToken");
  const headers: HeadersInit_ = {};
  if (token) {
      headers['Authorization'] = `Bearer ${token}`;
  }

  // 使用 fetch 代替 axios 进行文件上传
  const response = await fetch('http://gxuoabe.nnruibo.cn/app-api/infra/file/upload', {
      method: 'POST',
      body: formData,
      headers,
  });

  if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`上传失败: ${response.status} ${response.statusText} - ${errorText}`);
  }

  return response.json(); // 返回解析后的json数据
}

// 上传文件到预签名URL
export const uploadFileToPresignedUrl = async (
  uploadUrl: string,
  file: {
    uri: string
    type: string
    name: string
  }
) => {
  // 修复预签名URL中的主机地址，将127.0.0.1替换为手机可访问的地址
  let fixedUploadUrl = uploadUrl
  if (uploadUrl.includes('127.0.0.1:19001')) {
    // 替换为后端服务器的实际地址，去掉端口号
    fixedUploadUrl = uploadUrl.replace('127.0.0.1:19001', 'gxuoabe.nnruibo.cn')
  } else if (uploadUrl.includes('127.0.0.1')) {
    // 如果没有端口号，直接替换IP
    fixedUploadUrl = uploadUrl.replace('127.0.0.1', 'gxuoabe.nnruibo.cn')
  }

  console.log('原始上传URL:', uploadUrl)
  console.log('修复后上传URL:', fixedUploadUrl)

  // 读取文件数据
  const response = await fetch(file.uri)
  const blob = await response.blob()

  // 使用PUT方法上传，Content-Type为文件的MIME类型
  const uploadResponse = await fetch(fixedUploadUrl, {
    method: 'PUT',
    body: blob,
    headers: {
      'Content-Type': file.type,
    },
  })

  if (!uploadResponse.ok) {
    throw new Error(`上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`)
  }

  return uploadResponse
}